package com.zretc.demojparedis.commons.interceptor;

import com.zretc.demojparedis.controller.QuestionController;
import com.zretc.demojparedis.dao.AuthRedis;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * Created by admin on 2020/7/20.
 */
public class AuthInterceptor implements HandlerInterceptor {

    //创建一个日志记录对象
    Logger logger = LoggerFactory.getLogger(QuestionController.class);
    @Autowired
    private AuthRedis authRedis;

    /**
     * 处理权限的拦截方法
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        String token = request.getHeader("Authorization");
        logger.info("token :"+token);
        if (StringUtils.isEmpty(token)) {
            response.getWriter().print("用户未登录，请登录后操作！");
            return false;
        }
        Object loginStatus = authRedis.get(token);
        if( Objects.isNull(loginStatus)){
            response.getWriter().print("token错误，请查看！");
            return false;
        }
        return true;
    }

}